#pragma once
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class InetAddr
{
    // 网络IP转主机IP
    void IPNet2Host()
    {
        // 这里的转化我们不使用inet_ntoa，因为他还是不太安全的
        char buffer[1024];
        ::inet_ntop(AF_INET, &_in_addr.sin_addr.s_addr, buffer, sizeof(buffer) - 1);
        _ip = buffer;
    }
    // 网络端口号转主机端口号
    void PortNet2Host()
    {
        _port = ::ntohs(_in_addr.sin_port);
    }

public:
    // 构造函数
    InetAddr() = default;
    InetAddr(const sockaddr_in &addr) : _in_addr(addr)
    {
        IPNet2Host();
        PortNet2Host();
    }
    InetAddr(std::string ip, uint16_t port) : _ip(ip), _port(port)
    {
        _in_addr.sin_family = AF_INET;
        _in_addr.sin_port = ::htons(_port);
        _in_addr.sin_addr.s_addr = ::inet_addr(ip.c_str());
    }
    InetAddr(uint16_t port) : _port(port)
    {
        _in_addr.sin_family = AF_INET;
        _in_addr.sin_port = ::htons(_port);
        _in_addr.sin_addr.s_addr = INADDR_ANY; // 云服务器不允许被绑定
    }
    bool operator==(const InetAddr& addr)
    {
        return _ip==addr._ip&&_port==addr._port;
    }
    std::string Addr()
    {
        return Ip()+":"+std::to_string(Port());
    }
    std::string Ip() { return _ip; }
    uint16_t Port() { return _port; }
    struct sockaddr *NetAddr() { return (struct sockaddr *)&_in_addr; }
    socklen_t Len() { return sizeof(_in_addr); }

    ~InetAddr() {}

private:
    struct sockaddr_in _in_addr;
    std::string _ip;
    uint16_t _port;
};